﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using log4net;
using RealState.BLL;
using RealState.BusinessObjects;
using Geekees.Common.Controls;
using System.Data;
using RealState.Utils;
using System.IO;

namespace RealState.W.AdminControl
{
    public partial class NewsEdit : System.Web.UI.UserControl
    {
        protected ILog log = LogManager.GetLogger(typeof(NewsCreate));
        private NewsBLL m_NewsBLL;
        private News m_NewsDO;
        private CategoriesBLL m_CategoriesBLL;
        private static int selectedNode = 0;

        public void bindData()
        {
            if (!string.IsNullOrEmpty(Request.QueryString["ID"]))
            {
                m_CategoriesBLL = new CategoriesBLL();
                m_NewsBLL = new NewsBLL();
                m_NewsDO = new News();
                try
                {
                    DataTable pages = Converter.ToDataTable(m_CategoriesBLL.GetCategoriesType(1));
                    ViewState["pages"] = pages;
                    populateTreeView(pages);
                    m_NewsDO = m_NewsBLL.GetNews(Int32.Parse(Request.QueryString["ID"]));
                    txtTitle.Text = m_NewsDO.Title;
                    txtIntro.Text = m_NewsDO.Content;
                    txtContent.Text = Server.HtmlDecode(m_NewsDO.Description);
                    bindThum();
                    ddlThumbnail.SelectedValue = m_NewsDO.ImgPath;
                    if (m_NewsDO.IsActive == true)
                        ckActive.Checked = true;
                    selectedNode = Int32.Parse(m_NewsDO.CategoryId.ToString());
                    getSelectedNode(MainMenu.RootNode, selectedNode);
                }
                catch (Exception ex)
                {
                    log.Error(ex.Message);
                }
                finally
                {
                    m_CategoriesBLL = null;
                }
            }

        }

        protected void getSelectedNode(ASTreeViewNode parentNode, int parent)
        {

            foreach (ASTreeViewNode node in parentNode.ChildNodes)
            {
                if (Int32.Parse(node.NodeValue) == selectedNode)
                {
                    MainMenu.SelectNode(node.NodeValue);
                }
                getSelectedNode(node, parent);
            }
        }

        protected void getNodeByID(ASTreeViewNode parentNode, int parent, ref ASTreeViewNode returnValue)
        {
            try
            {

                foreach (ASTreeViewNode node in parentNode.ChildNodes)
                {
                    if (Int32.Parse(node.NodeValue) == parent)
                    {
                        returnValue = node;
                    }

                    getNodeByID(node, parent, ref returnValue);
                }
            }
            catch (Exception ex)
            {
                log.Error("getNodeByID: " + ex.Message);
            }
            finally
            {
            }
        }

        protected void populateTreeView(DataTable pages)
        {
            try
            {
                bool flag;
                pages.Columns.Add("inserted");
                MainMenu.RootNode.ChildNodes.Clear();
                MainMenu.RootNodeValue = "0";
                foreach (DataRow row in pages.Rows)
                {
                    string nodeText = row["TITLE"].ToString().Trim();
                    string nodeValue = row["ID"].ToString().Trim();

                    if (Int32.Parse(row["PARENTID"].ToString()) == 0)
                    {
                        ASTreeViewNode child = new ASTreeViewNode(nodeText, nodeValue, "~/AdminPanel/plugins/astree/astreeview/images/astreeview-folder-open.gif");
                        MainMenu.RootNode.AppendChild(child);
                    }
                }
                do
                {
                    flag = false;
                    foreach (DataRow row2 in pages.Rows)
                    {
                        string str4 = row2["TITLE"].ToString().Trim();
                        string str5 = row2["ID"].ToString().Trim();
                        int parent = Int32.Parse(row2["PARENTID"].ToString());

                        if ((parent > 0) && (row2["inserted"].ToString().Trim() == ""))
                        {
                            ASTreeViewNode node2 = new ASTreeViewNode(str4, str5, "~/AdminPanel/plugins/astree/astreeview/images/astreeview-folder-open.gif");
                            ASTreeViewNode returnValue = null;
                            getNodeByID(MainMenu.RootNode, parent, ref returnValue);
                            if (returnValue == null)
                            {
                                flag = true;
                            }
                            else
                            {
                                returnValue.AppendChild(node2);
                                row2["inserted"] = "1";
                            }
                        }
                    }
                }
                while (flag);
            }
            catch (Exception ex)
            {
                log.Error("populateTreeView" + ex.Message);
            }

        }

        private void bindThum()
        {
            ddlThumbnail.Items.Clear();
            string path = "~/upload/news/";
            string[] files = Directory.GetFiles(Server.MapPath(path));
            Action<string[], bool> action = delegate(string[] filde, bool forThumbs)
            {
                foreach (string str in files)
                {
                    string str5 = Path.GetExtension(str).ToLower();
                    string item = Path.GetFileName(str);
                    switch (str5)
                    {
                        case ".jpg":
                        case ".jpeg":
                        case ".png":
                        case ".gif":
                            if (forThumbs)
                            {
                                this.ddlThumbnail.Items.Add(item);
                            }
                            break;
                    }
                }
            };
            action(files, true);
        }

        protected void btnBindImagesThum_Click(object sender, EventArgs e)
        {
            string text = string.Empty;
            if (ddlThumbnail.SelectedIndex != -1)
            {
                text = ddlThumbnail.SelectedItem.Text.Trim();
            }
            bindThum();
            if (Session["uploaded_pic_thum"] != null)
            {
                string str3 = Session["uploaded_pic_thum"].ToString().Trim();
                Session["uploaded_pic_thum"] = null;
                if (Session["uploaded_pic_ext"] != null)
                {
                    if (Session["uploaded_pic_ext"].ToString().Trim().ToLower() == "thumb")
                    {
                        if (ddlThumbnail.Items.FindByText(str3) != null)
                        {
                            ddlThumbnail.SelectedIndex = -1;
                            ddlThumbnail.Items.FindByText(str3).Selected = true;
                        }

                    }

                    Session["uploaded_pic_ext"] = null;
                }
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                bindData();
               
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!Page.IsValid)
                return;
            ASTreeViewNode selectedNode = MainMenu.GetSelectedNode();
            if (selectedNode == null)
            {
                JavaScript.Error("Bạn chưa chọn danh mục !", this.Page);
                return;
            }
            m_NewsBLL = new NewsBLL();
            m_NewsDO = new News();
            try
            {
                m_NewsDO.Id = Int32.Parse(Request.QueryString["ID"]);
                m_NewsDO.Title = txtTitle.Text;
                m_NewsDO.ImgPath = ddlThumbnail.SelectedValue;
                if (ckActive.Checked)
                    m_NewsDO.IsActive = true;
                else
                    m_NewsDO.IsActive = false;
                m_NewsDO.IsRemove = false;
                m_NewsDO.CreatedTime = DateTime.Now;
                m_NewsDO.Content = txtIntro.Text;
                m_NewsDO.Description = Server.HtmlEncode(txtContent.Text);
                m_NewsDO.UserId = 1;
                m_NewsDO.CategoryId = Convert.ToInt32(selectedNode.NodeValue); 
                int result = m_NewsBLL.UpdateNews(m_NewsDO);
                if (result > 0)
                {
                    JavaScript.Success("Cập nhật thành công", Page, Request.Url.ToString());
                }
                else
                    JavaScript.Error("Có lỗi xảy ra ", Page);
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
            finally
            {
                m_NewsDO = null;
                m_NewsBLL = null;
            }
        }
    }
}